package com.example.demo.utils;

import com.example.demo.entity.Manager;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UserContext {
    private static final ThreadLocal<String> userContext = new ThreadLocal<>();
    private static final ThreadLocal<String> managerContext = new ThreadLocal<>();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void setUserId(String userId) {
        userContext.set(userId);
    }

    public static String getUserId() {
        return userContext.get();
    }

    public static void setManager(Manager manager) {
        try {
            managerContext.set(objectMapper.writeValueAsString(manager));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize manager object", e);
        }
    }

    public static Manager getManager() {
        String managerJson = managerContext.get();
        if (managerJson == null) {
            return null;
        }
        try {
            return objectMapper.readValue(managerJson, Manager.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to deserialize manager object", e);
        }
    }

    public static String getUsername() {
        return getManager().getUsername();
    }

    public static void clear() {
        userContext.remove();
        managerContext.remove();
    }
}
